package com.hulk.dryad.admin.filter;

import cn.hutool.core.util.StrUtil;
import com.anji.captcha.model.common.CaptchaTypeEnum;
import com.anji.captcha.model.vo.CaptchaVO;
import com.anji.captcha.service.CaptchaService;
import com.hulk.dryad.common.component.R;
import com.hulk.dryad.common.constant.CacheConstants;
import com.hulk.dryad.common.constant.SecurityConstants;
import com.hulk.dryad.common.constant.enums.BEC;
import com.hulk.dryad.common.exception.ValidateCodeException;
import com.hulk.dryad.common.util.SpringContextHolder;
import com.hulk.dryad.common.util.WebUtils;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @Classname ValidateCodeFilter
 * @Description 图形验证码过滤器
 * @Author hulk
 * @Date 2020-07-07 23:02
 */

@Slf4j
@Component
@RequiredArgsConstructor
public class ValidateCodeFilter extends OncePerRequestFilter implements  Ordered {


    private static final String IMAGE_CODE = "code";
    private static final String RANDOM_STR = "randomStr";
    private static final String MOBILE = "mobile";
    
    private final static AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    private final RedisTemplate redisTemplate;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)  throws IOException, ServletException {

        //要拦截的路径
		if (PATH_MATCHER.match(SecurityConstants.OAUTH_TOKEN_URL, request.getRequestURI())) {
			try {
				// 1. 进行验证码的校验
				checkCode(request);
			} catch (ValidateCodeException e) {
				WebUtils.renderJson(response,R.failed(BEC.E_2017));
			}
		}
        // 3. 通过放行
        chain.doFilter(request, response);
    }


    /**
     * 检查code
     *
     * @param request
     */
    @SneakyThrows
    private void checkCode(HttpServletRequest request) {
        String code = obtainImageCode(request);

        if (StrUtil.isBlank(code)) {
            throw new ValidateCodeException(BEC.E_2017);
        }

        String randomStr = obtainRandomStr(request);

        // 若是滑块登录
        if (CaptchaTypeEnum.BLOCKPUZZLE.getCodeValue().equalsIgnoreCase(randomStr)) {
            CaptchaService captchaService = SpringContextHolder.getBean(CaptchaService.class);
            CaptchaVO vo = new CaptchaVO();
            vo.setCaptchaVerification(code);
            if (!captchaService.verification(vo).isSuccess()) {
                throw new ValidateCodeException(BEC.E_2018);
            }
            return;
        }


        // 短信验证码校验 randomStrkey=手机号 randomStrvalue=验证码 与code比较
        String mobile = obtainMobile(request);
        if (StrUtil.isNotBlank(mobile)) {
            randomStr = mobile;
        }
        String key = CacheConstants.DEFAULT_CODE_KEY + randomStr;
        redisTemplate.setKeySerializer(new StringRedisSerializer());

        if (!redisTemplate.hasKey(key)) {
            throw new ValidateCodeException(BEC.E_2017);
        }

        Object codeObj = redisTemplate.opsForValue().get(key);

        if (codeObj == null) {
            throw new ValidateCodeException(BEC.E_2017);
        }

        String saveCode = codeObj.toString();
        if (StrUtil.isBlank(saveCode)) {
            redisTemplate.delete(key);
            throw new ValidateCodeException(BEC.E_2017);
        }

        if (!StrUtil.equals(saveCode, code)) {
            redisTemplate.delete(key);
            throw new ValidateCodeException(BEC.E_2017);
        }

        redisTemplate.delete(key);
    }


    /**
     * 获取前端传来的图片验证码
     *
     * @param request
     * @return
     */
    private String obtainImageCode(HttpServletRequest request) {
        return request.getParameter(IMAGE_CODE);
    }

    /**
     * 获取前端验证码类型
     *
     * @param request
     * @return
     */
    private String obtainRandomStr(HttpServletRequest request) {
        return request.getParameter(RANDOM_STR);
    }
    /**
     * 获取前端验证码类型
     *
     * @param request
     * @return
     */
    private String obtainMobile(HttpServletRequest request) {
        return request.getParameter(MOBILE);
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE - 800;
    }
}
